package com.zcx.excel.listen;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import com.zcx.excel.pojo.Price;
import com.zcx.excel.service.PriceService;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
@Slf4j
/**
 * @author zhaochangxin
 * @Title: PriceListener
 * @Package com.zcx.excel.listen
 * @Description: 读取PriceExcelListen类
 * @date 2022/3/28 11:39
 */
public class PriceListener implements ReadListener<Price> {

    private PriceService priceService;
    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 50;
    /**
     * 缓存的数据
     */
    private List<Price> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    public PriceListener(PriceService priceService) {
        this.priceService = priceService;
    }


    @Override
    public void invoke(Price price, AnalysisContext analysisContext) {
        log.info("解析到一条数据:{}", JSON.toJSONString(price));
        cachedDataList.add(price);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
        log.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        log.info("{}条数据，开始存储数据库！", cachedDataList.size());
        for (Price price : cachedDataList) {
            priceService.insertPrice(price);
        }
        log.info("存储数据库成功！");
    }
}